<?php

namespace app\data\controller\shop;

use app\data\model\BaseUserDiscount;
use app\data\model\BaseUserPayment;
use app\data\model\BaseUserUpgrade;
use app\data\model\ShopGoods;
use app\data\model\ShopGoodsBrandRela;
use app\data\model\ShopGoodsBrand;
use app\data\model\ShopGoodsCate;
use app\data\model\ShopGoodsCateRela;
use app\data\model\ShopGoodsItem;
use app\data\model\ShopGoodsMark;
use app\data\model\ShopGoodsService;
use app\data\model\ShopGoodsStock;
use app\data\service\ExpressService;
use app\data\service\GoodsService;
use think\admin\Controller;
use think\admin\extend\CodeExtend;

/**
 * 商品数据管理
 * Class Goods
 * @package app\data\controller\shop
 */
class Goods extends Controller
{
    /**
     * 商品数据管理
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $this->title = '商品数据管理';

        $query = ShopGoods::mQuery();
        // 加载对应数据
        $this->type = $this->request->get('type', 'index');
        if ($this->type === 'index') $query->whereIn('status','0,1');
        elseif ($this->type === 'recycle') $query->where(['status' => 2]);
        else $this->error("无法加载 {$this->type} 数据列表！");

        // 列表排序并显示
        $query->like('code|name#name')->like('cateids');
        $lists = $query->equal('status')->order('sort desc,id desc')->page();
    }

    /**
     * 商品选择器
     * @login true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function select()
    {
        $query = ShopGoods::mQuery();
        $query->equal('status')->like('code,name,marks')->in('cateids');
        $query->where(['deleted' => 0])->order('sort desc,id desc')->page();
    }

    /**
     * 数据列表处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _page_filter(array &$data)
    {
        $this->cates = ShopGoodsCate::treeTable();
        GoodsService::bindData($data, false);
    }

    /**
     * 添加商品数据
     * @auth true
     */
    public function add()
    {
        $this->addtype = 1;
        $this->mode = 'add';
        $this->title = '添加商品数据';
        ShopGoods::mForm('form', 'code');
    }

    /**
     * 编辑商品数据
     * @auth true
     */
    public function edit()
    {
        $this->addtype = 0;
        $this->mode = 'edit';
        $this->title = '编辑商品数据';
        ShopGoods::mForm('form', 'code');
    }

    /**
     * 复制编辑商品
     * @auth true
     */
    public function copy()
    {
        $this->mode = 'copy';
        $this->title = '复制编辑商品';
        ShopGoods::mForm('form', 'code');
    }

    /**
     * 表单数据处理
     * @param array $data
     */
    protected function _copy_form_filter(array &$data)
    {
        if ($this->request->isPost()) {
            $data['code'] = CodeExtend::uniqidNumber(20, 'G');
        }
    }

    /**
     * 表单数据处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _form_filter(array &$data)
    {
        if (empty($data['code'])) {
            $data['code'] = CodeExtend::uniqidNumber(20, 'G');
        }
        if ($this->request->isGet()) {
            $data['marks'] = str2arr($data['marks'] ?? '');
//            $data['cateids'] = str2arr($data['cateids'] ?? '');
            $cateLists = [];
            $cateIds = [];
            if(isset($data['id'])){
                $cateLists = ShopGoodsCateRela::mk()->alias('gc')
                    ->leftJoin('shop_goods_cate sc',"gc.cate_id = sc.id")
                    ->where([
                        'gc.goods_id'   => $data['id'],
                        'sc.status'     => 1
                ])->field('sc.name,sc.id')->select()->toArray();
                if(empty($cateLists) === FALSE){
                    foreach($cateLists as &$cv){
                        array_push($cateIds,$cv['id']);
                    }
                }
            }
            $this->cateLists = $cateLists;
            $this->cateIds = implode(',',$cateIds);
            // 其他表单数据
            $this->cates = ShopGoodsCate::treeTable(true);
            // 商品规格处理
            $fields = 'goods_sku `sku`,sort,goods_code,goods_spec `key`,price_selling `selling`,price_market `market`,number_virtual `virtual`,status,cover,name,stock_total';
            $data['data_items'] = ShopGoodsItem::mk()->where(['goods_code' => $data['code'],'status'=>1])->column($fields);
            $data['data_specs'] = ShopGoodsItem::mk()->where(['goods_code' => $data['code']])->column('goods_spec');
            $res = [];
            if(empty($data['data_items'])){
                $data['data_items'][] = array(
                    'id'    => '',
                    'sku'    => \Common::createSku(14,'S'),
                    'goods_code'    => '',
                    'key'    => '',
                    'selling'    => '',
                    'market'    => '',
                    'virtual'    => '',
                    'cover'    => '',
                    'status'    => 0,
                    'stock_total'    => 0,
                    'name'    => 0,
                    'sort'    => 0,
                );
            }else{
                foreach ($data['data_items'] as &$ditemv){
                    $ditemv['selling'] = sprintf("%.2f",$ditemv['selling']/100);
                    $ditemv['market'] = sprintf("%.2f",$ditemv['market']/100);
                }
            }
            if(empty($data['service']) === FALSE){
                $data['service'] = json_decode($data['service'],true);
            }else{
                $data['service'] = array(array(
                    'name'  => '请选择',
                    'summary'=>'',
                    'service_id'    => ''
                ));
            }
            //平台服务
            $services = ShopGoodsService::mk()->where(['status' => 1])->select()->toArray();
            $data['services'] = $services;
            if(!isset($data['state_hot'])) $data['state_hot'] = 0;
            if(!isset($data['state_home'])) $data['state_home'] = 0;
            if(!isset($data['can_drawback'])) $data['can_drawback'] = 0;
            //获取所属品牌
            $data['brand_id'] = 0;
            if(empty($data['id']) === FALSE){
                $brandInfo = ShopGoodsBrandRela::mk()->where(array(
                    'goods_id'  =>$data['id']
                ))->field('brand_id')->find();
                if(empty($brandInfo) === FALSE){
                    $data['brand_id'] = $brandInfo['brand_id'];
                }
            }
            $brands = ShopGoodsBrand::mk()->where(array(
                'status'    =>1
            ))->select()->toArray();
            $data['brands'] = $brands;

        } elseif ($this->request->isPost()) {
            if (empty($data['cover'])) $this->error('商品图片不能为空！');
            if (empty($data['slider'])) $this->error('轮播图片不能为空！');

            if(!isset($data['state_hot'])) $data['state_hot'] = 0;
            if(!isset($data['state_home'])) $data['state_home'] = 0;
            $data['create_at'] = \Tools::getDateTimeByTime();
            $data['update_at'] = \Tools::getDateTimeByTime();
            // 商品规格保存
            [$data['price_market'], $data['price_selling']] = [0, 0];
            $goodsNum = 0;
            $goodsVirtual = 0;
            if(empty($data['itemname']) === FALSE) {
                foreach ($data['itemname'] as $ik => $item) {
                    $goodsNum += $data['stock_total'][$ik]??0;
                    $goodsVirtual += $data['virtual'][$ik]??0;
                    if ($data['price_market'] === 0 || $data['price_market'] > $data['market'][$ik]*100) $data['price_market'] = $data['market'][$ik]*100;
                    if ($data['price_selling'] === 0 || $data['price_selling'] > $data['selling'][$ik]*100) $data['price_selling'] = $data['selling'][$ik]*100;
                }
            }
            if (empty($goodsNum)) $this->error('无效的商品库存信息！');
            //获取服务
            $serviceid = $data['service'];
            $sinfo = ShopGoodsService::mk()->whereIn('service_id',$serviceid)->field('service_id,name,summary')->group('service_id')->select()->toArray();
            $data['service'] = json_encode($sinfo);
            ShopGoodsItem::mk()->where(['goods_code' => $data['code']])->update(['status' => 0]);
            foreach ($data['itemname'] as $ik=>$item) data_save(ShopGoodsItem::class, [
                'goods_sku'       => $data['sku'][$ik],
                'goods_spec'      => $data['skumodel'][$ik],
                'goods_code'      => $data['code'],
                'price_market'    => $data['market'][$ik]*100,
                'stock_total'    => $data['stock_total'][$ik],
                'price_selling'   => $data['selling'][$ik]*100,
                'number_virtual'  => $data['virtual'][$ik]??0,
                'create_at'  => \Tools::getDateTimeByTime(),
                'update_at'  => \Tools::getDateTimeByTime(),
                'status'          => $data['status'][$ik]??0 ? 1 : 0,
                'cover'             => $data['itemcover1'][$ik],
                'name'              => $item,
                'sort'              =>$data['sort'][$ik]??0
            ], 'goods_spec', [
                'goods_code' => $data['code'],
            ]);
            $data['marks'] = arr2str($data['marks'] ?? []);
            $data['stock_total'] = $goodsNum;
            $data['smail_cover'] = $data['cover'];
            $data['stock_virtual'] = $goodsVirtual;
        }
    }

    /**
     * 表单结果处理
     * @param boolean $result
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _form_result(bool $result,$data)
    {
        if ($result && $this->request->isPost()) {
            $goodsid = ShopGoods::mk()->where(array('code'  => $data['code']))->find();
            $goodsid = $goodsid['id'];
            //保存分类关系
            $cateids = $data['cateids'];
            //删除分类商品
            ShopGoodsCateRela::mk()->where(array(
                'goods_id' => $goodsid
            ))->delete();
            if(empty($cateids) === FALSE){
                $cateids = trim($cateids,',');
                $cateids = explode(",",$cateids);
//                $cateids = explode(',',$cateids);
//                $cateid = $cateids[count($cateids)-1];
                foreach($cateids as &$cateid) {
                    //获取商品是否存在
                    $cateinfo = ShopGoodsCateRela::mk()->where(array(
                        'goods_id' => $goodsid,
                        'cate_id' => $cateid
                    ))->find();
                    if (empty($cateinfo)) {
                        $lastCate = ShopGoodsCateRela::mk()->order(array('sort' => 'desc'))->field('sort')->find();
                        if (empty($lastCate)) $lastCate['sort'] = 0;
                        $cate_data = array(
                            'goods_id' => $goodsid,
                            'cate_id' => $cateid,
                            'create_at' => \Tools::getDateTimeByTime(),
                            'sort' => $lastCate['sort'] + 1
                        );
                        ShopGoodsCateRela::mk()->save($cate_data);
                    }
                }
            }
            //关联品牌
            $brand_id = $data['brand'];
            if(empty($brand_id) === FALSE){
                $brandinfo = ShopGoodsBrandRela::mk()->where(array(
                    'goods_id'  =>$goodsid
                ))->find();
                if(empty($brandinfo)){
                    $lastbrand = ShopGoodsBrandRela::mk()->order(array('sort'=>'desc'))->field('sort')->find();
                    if(empty($lastbrand)) $lastbrand['sort'] = 0;
                     $brand_data = array(
                        'goods_id'  => $goodsid,
                        'brand_id'  => $brand_id,
                        'create_at'  => \Tools::getDateTimeByTime(),
                        'sort' => $lastbrand['sort']+1
                     );
                     ShopGoodsBrandRela::mk()->save($brand_data);
                }else{
                    if($brandinfo['brand_id'] != $brand_id){
                        $lastbrand = ShopGoodsBrandRela::mk()->order(array('sort'=>'desc'))->field('sort')->find();
                        if(empty($lastbrand)) $lastbrand['sort'] = 0;
                         $brand_data = array(
                            'goods_id'  => $goodsid,
                            'brand_id'  => $brand_id,
                            'create_at'  => \Tools::getDateTimeByTime(),
                            'sort' => $lastbrand['sort']+1
                         );
                         ShopGoodsBrandRela::mk()->update($brand_data,['id'=>$brandinfo['id']])->save();
                    }
                }
            }
            $this->success('商品编辑成功！', 'javascript:history.back()');
        }
    }

    /**
     * 商品库存入库
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function stock()
    {
        $map = $this->_vali(['code.require' => '商品编号不能为空哦！']);
        if ($this->request->isGet()) {
            $list = ShopGoods::mk()->where($map)->select()->toArray();
            if (empty($list)) $this->error('无效的商品数据，请稍候再试！');
            [$this->vo] = GoodsService::bindData($list);
            $this->fetch();
        } else {
            [$data, $post] = [[], $this->request->post()];
            $all_num = 0;
            $opera = [];
            ShopGoods::mk()->startTrans();
            $detail = '';
            if (isset($post['goods_code']) && is_array($post['goods_code'])) {
                foreach (array_keys($post['goods_code']) as $key) {
                    if ($post['goods_stock'][$key] > 0) {
                        $opera[] = ShopGoodsItem::mk()->where(array(
                            'id'    => $post['itemid'][$key]
                        ))->inc('stock_total',$post['goods_stock'][$key])->save();
                        $all_num += $post['goods_stock'][$key];
                        $detail .= $post['goods_spec'][$key].':'.$post['goods_stock'][$key].'件;';
                    }
                }
                $opera[] = ShopGoods::mk()->where(array(
                    'code'  => $post['goods_code'][0]
                ))->inc('stock_total',$all_num)->save();

                sysoplog('商品入库', '商品'.$post['goods_code'][0].'入库：'.$all_num.'件:分别为：'.$detail);

                if (\Tools::checkArrayResult($opera)) {
                    ShopGoods::mk()->commit();
                    $this->success('商品数据入库成功！');
                }else{
                    ShopGoods::mk()->rollBack();
                    return \Tools::returnMsg(false,array(
                        'code'  => '10005',
                        'message'   => '入库失败'
                    ),'json');
                }
            }
            $this->error('没有需要商品入库的数据！');
        }
    }

    /**
     * 商品上下架
     * @auth true
     */
    public function state()
    {
        ShopGoods::mSave($this->_vali([
            'status.in:0,1'  => '状态值范围异常！',
            'status.require' => '状态值不能为空！',
        ]), 'code');
    }

    /**
     * 删除商品数据
     * @auth true
     */
    public function remove()
    {
        $code = input('code','');
        if(empty($code)) return \Tools::returnMsg(false,array(
            'code'  =>'10004',
            'message'=>'参数错误'
        ),'json');
        $opera = [];
        ShopGoods::mk()->startTrans();
        $codes = explode(',', $code);
        foreach($codes as &$code) {
            $product_id = ShopGoods::mk()->where(['code' => $code])->value('id');
            $opera[] = ShopGoods::mk()->where(['code' => $code])->delete();
            //查询子商品
            $child_goods = ShopGoodsItem::mk()->where(['goods_code' => $code])->find();
            if (empty($child_goods) === FALSE) {
                $opera[] = ShopGoodsItem::mk()->where(['goods_code' => $code])->delete();
            }
            //查找品牌  分类  进行删除
            $brand = ShopGoodsBrandRela::mk()->where(['goods_id' => $product_id])->find();
            if (empty($brand) === FALSE) $opera[] = ShopGoodsBrandRela::mk()->where(['goods_id' => $product_id])->delete();
            $cate = ShopGoodsCateRela::mk()->where(['goods_id' => $product_id])->find();
            if (empty($cate) === FALSE) $opera[] = ShopGoodsCateRela::mk()->where(['goods_id' => $product_id])->delete();
        }
        if(\Tools::checkArrayResult($opera)){
            ShopGoods::mk()->commit();
            return \Tools::returnMsg(true,$opera,'json');
        }else{
            ShopGoods::mk()->rollBack();
            return \Tools::returnMsg(false,array(
                'code'  =>'10004',
                'message'=>'参数错误'
            ),'json');
        }
    }
       /**
     * 下载二维码
     * @return void
     */
    public function download(){
        $code = input('code','','trim,intval');
        if(empty($id)) $this->error('信息有误');
        $info = DataWechat::info(array(
            'id'=>$id
        ),'qrcode_path');
        if(empty($info) || empty($info['qrcode_path'])) $this->error('信息有误');
        \Common::downloadQrcode($info);
    }
}
